import 'dart:async';
import 'dart:convert';
import 'package:applications/module/home/bean/application_bean.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final apiService = Provider((ref) => ApplicationsAPI());

const String baseApi = "https://itunes.apple.com/";
const String languageCode = "hk";

class ApplicationsAPI {
  /// 最受歡迎的Apps
  Future<List<Entry>> topgrossing({int limit = 10}) async {
    var dio = Dio(BaseOptions(
      connectTimeout: 30000,
      receiveTimeout: 30000,
      contentType: Headers.jsonContentType,
      responseType: ResponseType.json,
      validateStatus: (status) => status! >= 200 && status < 400,
    ));
    var response = await dio.get(
        '$baseApi/$languageCode/rss/topgrossingapplications/limit=$limit/json');
    var bean = ApplicationBean.fromJson(jsonDecode(response.data));
    return bean.feed?.entry ?? [];
  }

  /// 下載量最多的免費App
  Future<List<Entry>> topfree({int limit = 100}) async {
    var dio = Dio(BaseOptions(
      connectTimeout: 30000,
      receiveTimeout: 30000,
      contentType: Headers.jsonContentType,
      responseType: ResponseType.json,
      validateStatus: (status) => status! >= 200 && status < 400,
    ));
    var urlPath =
        '$baseApi/$languageCode/rss/topfreeapplications/limit=$limit/json';
    var response = await dio.get(urlPath);
    var bean = ApplicationBean.fromJson(jsonDecode(response.data));
    return bean.feed?.entry ?? [];
  }

  /// 获取App的评级数与评级分数
  Future<Map<String, dynamic>> lookup({required int id}) async {
    var dio = Dio(BaseOptions(
      connectTimeout: 30000,
      receiveTimeout: 30000,
      contentType: "text/javascript; charset=utf-8",
      responseType: ResponseType.bytes,
      validateStatus: (status) => status! >= 200 && status < 400,
    ));
    var response =
        await dio.get<List<int>>('$baseApi/$languageCode/lookup?id=$id');
    return compute(_generatorRating, response.data);
  }

  Map<String, dynamic> _generatorRating(List<int>? data) {
    if (data == null) {
      return {
        'averageUserRating': 0,
        'userRatingCount': 0,
        'description': '',
        'artistName': '',
      };
    }
    var jsonStr = utf8.decode(data);
    var map = jsonDecode(jsonStr);
    double? averageUserRating = double.parse(map['results']
            ?.first['averageUserRatingForCurrentVersion']
            .toString() ??
        '0');
    int? userRatingCount =
        map['results']?.first['userRatingCountForCurrentVersion'];
    String? description = map['results']?.first['description'];
    String? artistName = map['results']?.first['artistName'];
    return {
      'averageUserRating': averageUserRating,
      'userRatingCount': userRatingCount ?? 0,
      'description': description ?? '',
      'artistName': artistName ?? '',
    };
  }
}
